<script setup lang="ts">
import {onMounted, reactive, ref} from "vue";
import {ElMessage, ElMessageBox, UploadProps} from 'element-plus'
import {QuestionControllerService, QuestionListVO, SetControllerService, SetGroupDTO} from "../../../../generated";
import TableToolBar from "../../../components/TableToolBar.vue";
import {useRoute, useRouter} from "vue-router";
import {Plus} from "@element-plus/icons-vue";

interface TableItem {
  id?: string;
  title?: string;
  rate?: string;
  tag?: {
    type: string;
    value: string;
  };
}

interface DataType {
  id?: string,
  title?: string,
  target?: string,
  description?: string,
  tagList?: string[],
  groups: QuestionGroup[]
}

// 新增题组接口定义
interface QuestionGroup {
  id: number;
  title: string;
  questions: TableItem[];
}

// 修改筛选条件的接口定义
interface FilterConditions {
  difficulty: string
  status: number | ''
  tag: string[]
  questionSet: string
  searchInput: string
}

interface QueryParams {
  currentPage: number;
  pageSize: number;
  difficulty?: number;
  status?: number;
  tags?: string[];
  questionSet?: string;
  searchText?: string;
}

// 修改 form 定义，添加 groups 字段
let form = reactive<DataType>({
  id: "",
  title: "",
  target: "",
  description: "",
  tagList: [],
  groups: [
    {
      id: 1,
      title: "默认题组",
      questions: []
    }
  ]
})

const tableData = ref<TableItem[]>([]);

const difficultyMap = {
  0: {type: "success", value: "简单"},
  1: {type: "warning", value: "中等"},
  2: {type: "danger", value: "困难"}
};

const tagOptions = ref([
  {label: '算法', value: '算法'},
  {label: '数据结构', value: '数据结构'},
  {label: '数学', value: '数学'},
  {label: '字符串', value: '字符串'},
  {label: '动态规划', value: '动态规划'},
  {label: '回溯', value: '随俗'}
]);

// 修改筛选条件的初始值
const filterConditions = ref<FilterConditions>({
  difficulty: '',
  status: 0,  // 设置默认值为 0，表示"未开始"
  tag: [],
  questionSet: '',
  searchInput: ''
})

const questionTableRef = ref();

let router = useRouter();
let route = useRoute();

// 新增当前选中的题组 id
const currentGroupId = ref(1)

const handleSubmit = async () => {
  console.log(form);
  const submitData = {
    ...form,
    groups: form.groups.map(group => ({
      title: group.title,
      questions: group.questions.map(q => q.id)
    })) as SetGroupDTO[],
    cover: imageUrl.value
  };
  let res = await SetControllerService.updateSetUsingPost(submitData);
  if (res.code === 0 && res.data) {
    await router.push("/studyplan/" + route.params.id)
  } else {
    ElMessage.error(res.message)
  }
}

const handleRowSelect = (selection: TableItem[], row: TableItem) => {
  const currentGroup = form.groups.find(g => g.id === currentGroupId.value)
  if (!currentGroup) return

  // 单个选择的处理逻辑
  const questionIndex = currentGroup.questions.findIndex(q => q.id === row.id)
  const isSelected = selection.some(item => item.id === row.id)

  if (questionIndex !== -1 && !isSelected) {
    // 如果题目在题组中且被取消选中，则从题组中移除
    currentGroup.questions.splice(questionIndex, 1)
  } else if (questionIndex === -1 && isSelected) {
    // 如果题目不在题组中且被选中，则添加到题组中
    currentGroup.questions.push(row)
  }
}

const handleSelectAll = (selection: TableItem[]) => {
  const currentGroup = form.groups.find(g => g.id === currentGroupId.value)
  if (!currentGroup) return

  // 获取当前页面所有题目的 ID 集合
  const currentPageIds = new Set(tableData.value.map(item => item.id))

  // 如果是全选操作
  if (selection.length > 0) {
    // 添加所有不在当前题组中的题目
    selection.forEach(item => {
      if (!currentGroup.questions.some(q => q.id === item.id)) {
        currentGroup.questions.push(item)
      }
    })
  } else {
    // 如果是取消全选，移除当前页面的所有题目
    currentGroup.questions = currentGroup.questions.filter(
        question => !currentPageIds.has(question.id)
    )
  }
}

// 处理筛选条件更新
const handleFilterUpdate = async (filters: {
  difficulty: string,
  status: number | '',
  tag: string[],
  questionSet: string,
  searchInput: string
}) => {
  filterConditions.value = filters as FilterConditions
  await loadQuestions()
}

const toQuestionDetail = (id: number) => {
  router.push("/question/detail?id=" + id)
}

// 添加分页相关的状态
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 添加一个反向映射对象
const difficultyReverseMap: Record<string, number> = {
  "easy": 0,
  "medium": 1,
  "hard": 2
};

const loadQuestions = async () => {
  // 构建查询参数
  const params: QueryParams = {
    currentPage: currentPage.value,
    pageSize: pageSize.value,
  }

  // 添加筛选条件
  if (filterConditions.value.difficulty) {
    // 将文字难度转换为对应的数字
    params.difficulty = difficultyReverseMap[filterConditions.value.difficulty];
  }
  if (filterConditions.value.status) {
    params.status = filterConditions.value.status;
  }
  if (filterConditions.value.tag && filterConditions.value.tag.length > 0) {
    params.tags = filterConditions.value.tag;
  }
  if (filterConditions.value.questionSet) {
    params.questionSet = filterConditions.value.questionSet;
  }
  if (filterConditions.value.searchInput) {
    params.searchText = filterConditions.value.searchInput;
  }

  const res = await QuestionControllerService.pageQuestionsUsingPost(params);
  tableData.value = res.data.records.map((item: QuestionListVO) => ({
    id: item.id,
    title: item.title,
    rate: item.rate,
    tag: difficultyMap[item.difficulty as keyof typeof difficultyMap]
  }));
  total.value = res.data.total
}

// 添加更新表格选中状态的方法
const updateTableSelection = () => {
  const currentGroup = form.groups.find(g => g.id === currentGroupId.value)
  if (currentGroup) {
    // 清空当前选中状态
    questionTableRef.value?.clearSelection()

    // 设置当前页面中属于当前题组的题目的选中状态
    const selectedIds = new Set(currentGroup.questions.map(q => q.id))
    tableData.value.forEach(row => {
      if (selectedIds.has(row.id)) {
        questionTableRef.value?.toggleRowSelection(row, true)
      }
    })
  }
}

// 修改分页变化处理方法
const handleCurrentChange = async (val: number) => {
  currentPage.value = val
  await loadQuestions()
  updateTableSelection()
}

// 修改页面大小变化处理方法
const handleSizeChange = async (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  await loadQuestions()
  updateTableSelection()
}

onMounted(async () => {
  let res = await SetControllerService.getSetDetailUsingGet(route.params.id as string);
  if (res.code === 0 && res.data) {
    // 更新基本信息
    form.id = res.data.id;
    form.title = res.data.title;
    form.target = res.data.target;
    form.description = res.data.description;
    form.tagList = res.data.tagList;

    // 更新题组信息
    if (res.data.groupList) {
      form.groups = res.data.groupList.map((group, index) => ({
        id: index + 1,
        title: group.title || '',
        questions: group.questionList?.map(q => ({
          id: q.id,
          title: q.title || '',
          tag: difficultyMap[q.difficulty as keyof typeof difficultyMap]
        })) || []
      }));
    }

    // 更新封面
    if (res.data.cover) {
      imageUrl.value = res.data.cover;
    }

    // 设置当前选中的题组为第一个题组
    currentGroupId.value = 1;
  }

  await loadQuestions();
  // 更新表格选中状态
  updateTableSelection();
})

// 添加新题组
const addGroup = () => {
  const newId = Math.max(...form.groups.map(g => g.id)) + 1
  form.groups.push({
    id: newId,
    title: `题组 ${newId}`,
    questions: []
  })
}

// 选择题组进行编辑
const selectGroup = (groupId: number) => {
  currentGroupId.value = groupId
  // 清空表格选择
  questionTableRef.value?.clearSelection()
  // 设置当前题组的题目选中状态
  const currentGroup = form.groups.find(g => g.id === groupId)
  if (currentGroup) {
    currentGroup.questions.forEach(question => {
      const tableRow = tableData.value.find(row => row.id === question.id)
      if (tableRow) {
        questionTableRef.value?.toggleRowSelection(tableRow, true)
      }
    })
  }
}

// 删除题组
const removeGroup = (groupId: number) => {
  const index = form.groups.findIndex(g => g.id === groupId)
  if (index !== -1) {
    form.groups.splice(index, 1)
    if (currentGroupId.value === groupId) {
      currentGroupId.value = form.groups[0].id
    }
  }
}

// 从题组中移除题目
const removeQuestionFromGroup = (groupId: number, questionIndex: number) => {
  const group = form.groups.find(g => g.id === groupId)
  if (group) {
    const question = group.questions[questionIndex]
    group.questions.splice(questionIndex, 1)
    // 更新表格选择状态
    const tableRow = tableData.value.find(row => row.id === question.id)
    if (tableRow) {
      questionTableRef.value?.toggleRowSelection(tableRow, false)
    }
  }
}

const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    _uploadFile
) => {
  if (response.code === 0 && response.data) {
    imageUrl.value = response.data
  } else {
    ElMessage.error('图片上传失败')
    ElMessage.error(response.message)
  }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

const handleDelete = async () => {
  let res = await SetControllerService.deleteSetUsingPost({
    id: route.params.id as string
  });
  if (res.code === 0 && res.data) {
    ElMessage.success('删除成功')
    await router.push('/problem')
  } else {
    ElMessage.error(res.message)
  }
}

const open = () => {
  ElMessageBox.confirm(
      '是否确认删除?该操作无法撤销',
      '删除题集',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        handleDelete()
      })
}
</script>

<template>
  <div class="update-question-set-container">
    <div class="page-header">
      <h2>更新题集</h2>
      <div>
        <el-button type="danger" @click="open">删除</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </div>

    <div class="main-section">
      <span class="label">题集标题</span><span class="required-asterisk">*</span>
      <el-input
          v-model="form.title"
          placeholder="请输入题目标题"
          :maxlength="100"
          show-word-limit
      />
      <span class="label" style="margin-top: 20px">目标</span>
      <el-input
          v-model="form.target"
          placeholder="请输入目标"
          :maxlength="50"
          show-word-limit
      />
      <span class="label" style="margin-top: 20px">描述</span>
      <el-input
          v-model="form.description"
          placeholder="请输入描述"
          type="textarea"
          :maxlength="200"
          show-word-limit
      />
      <span class="label" style="margin-top: 20px">标签</span>
      <div class="tags-container">
        <el-select
            v-model="form.tagList"
            multiple
            filterable
            allow-create
            default-first-option
            :reserve-keyword="false"
            placeholder="请选择或输入标签"
            style="width: 100%"
        >
          <el-option
              v-for="item in tagOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </div>
      <span class="label" style="margin-top: 20px">封面</span>
      <el-upload
          class="avatar-uploader"
          action="http://localhost:8080/api/files/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="封面"/>
        <el-icon v-else class="avatar-uploader-icon">
          <Plus/>
        </el-icon>
      </el-upload>
      <span class="label" style="margin-top: 20px">题组管理</span>
      <div class="question-groups">
        <div class="groups-header">
          <el-button type="primary" @click="addGroup">添加题组</el-button>
        </div>

        <div class="groups-list">
          <el-card v-for="group in form.groups" :key="group.id" class="group-card" shadow="never">
            <div class="group-header">
              <div class="group-title">
                <div class="title-label">标题：</div>
                <el-input
                    v-model="group.title"
                    placeholder="请输入题组标题"
                    :disabled="currentGroupId !== group.id"
                    size="small"
                />
              </div>
              <div class="group-actions">
                <el-button
                    type="primary"
                    size="small"
                    @click="selectGroup(group.id)"
                    :disabled="currentGroupId === group.id"
                >
                  编辑
                </el-button>
                <el-button
                    type="danger"
                    size="small"
                    @click="removeGroup(group.id)"
                    v-if="form.groups.length > 1"
                >
                  删除
                </el-button>
              </div>
            </div>
            <div class="group-questions">
              <div v-for="(question, index) in group.questions" :key="question.id" class="question-item">
                <span>{{ question.title }}</span>
                <el-tag :type="question.tag?.type">{{ question.tag?.value }}</el-tag>
                <el-button
                    type="danger"
                    size="small"
                    @click="removeQuestionFromGroup(group.id, index)"
                    v-if="currentGroupId === group.id"
                >
                  移除
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>

    <TableToolBar @update-filters="handleFilterUpdate" :show-random-button="false" :show-status="false"/>

    <el-table
        ref="questionTableRef"
        :data="tableData"
        style="width: 100%"
        @select="handleRowSelect"
        @select-all="handleSelectAll"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="title" label="题目" align="center">
        <template #default="scope">
          <a class="row-title" @click="toQuestionDetail(scope.row.id)">{{ scope.row.title }}</a>
        </template>
      </el-table-column>
      <el-table-column prop="rate" label="通过率" align="center"/>
      <el-table-column prop="tag" label="难度" align="center">
        <template #default="scope">
          <el-tag
              :type="scope.row.tag.type"
              disable-transitions
          >{{ scope.row.tag.value }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改分页容器 -->
    <div class="pagination-container">
      <div class="page-sizes">
        <el-select
            v-model="pageSize"
            @change="handleSizeChange"
        >
          <el-option
              v-for="size in [10, 50, 100]"
              :key="size"
              :value="size"
              :label="`${size}条/页`"
          />
        </el-select>
      </div>
      <div class="page-nav">
        <el-pagination
            v-model:current-page="currentPage"
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

</template>

<style scoped>
.main-section {
  background: var(--el-bg-color);
  border-radius: 8px;
  padding: 24px;
  border: 1px solid rgba(0, 0, 0, 0.15);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.label {
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  padding-bottom: 12px;
  position: relative;
  display: inline-block;
}

.label::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 6px;
  width: 24px;
  height: 2px;
  background-color: var(--el-color-primary);
  border-radius: 1px;
}

.update-question-set-container {
  padding: 0 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  position: relative;
  padding-left: 16px;
}

.page-header h2::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background-color: var(--el-color-primary);
  border-radius: 2px;
}

.required-asterisk {
  color: var(--el-color-danger);
  margin-left: 4px;
}

.tags-container {
  margin-top: 8px;
  margin-bottom: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-sizes {
  flex-shrink: 0;
  width: 120px;
}

.page-nav {
  flex-shrink: 0;
}

.question-groups {
  margin-top: 16px;
}

.groups-header {
  margin-bottom: 16px;
}

.group-card {
  margin-bottom: 16px;
}

.group-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  gap: 16px;
}

.group-title {
  flex: 1;
  max-width: 300px; /* 限制输入框最大宽度 */
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-label {
  white-space: nowrap;
  color: var(--el-text-color-regular);
  font-size: 14px;
}

.group-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0; /* 防止按钮被压缩 */
}

.group-questions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.question-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 4px;
}

.question-item span {
  flex: 1;
}

.avatar-uploader .avatar {
  width: 130px;
  height: 130px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 130px;
  text-align: center;
}
</style>
